package de.uni.bremen.estudent.lbs.fragments;


import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

import de.uni.bremen.estudent.lbs.R;
import de.uni.bremen.estudent.lbs.provider.EstudentLBSContract.Categories;
import de.uni.bremen.estudent.lbs.util.CategoryListAdapter;


/**
 * @author bahlfeld
 * @version 1.0 23.01.2012
 */
public final class CategoryFragment extends ListFragment implements
                                                        LoaderCallbacks<Cursor> {

    /**
     * These are the category rows that we will retrieve.
     */
    static final String[] CATEGORY_SUMMARY_PROJECTION = new String[] {
            Categories.CATEGORY_ID, Categories.CATEGORY_NAME };
    /**
     * Column names of the category.
     */
    private final String[] from = new String[] { Categories.CATEGORY_NAME };

    /**
     * Cursor adapter connects data and view.
     */
    private CategoryListAdapter mAdapter;

    /**
     * Ids of the categorylistitem.
     */
    private final int[] to = new int[] { R.id.categoryCheckBox };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setEmptyText("No categories found");

        /**
         * Adapter with empty cursor.
         */
        mAdapter = new CategoryListAdapter(getActivity(),
                                        R.layout.fragment_categorylist_item,
                                        null, from, to, 0);
        setListAdapter(mAdapter);

        LoaderManager lm = getLoaderManager();
        if (lm != null) {
            lm.initLoader(0, null, this);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(final int arg0, final Bundle arg1) {
        Uri baseUri = Categories.CONTENT_URI;

        String select = "";

        return new CursorLoader(getActivity().getApplicationContext(), baseUri,
                                        CATEGORY_SUMMARY_PROJECTION, select,
                                        null, " COLLATE LOCALIZED ASC");
    }

    @Override
    public void onLoaderReset(final Loader<Cursor> arg0) {
        mAdapter.swapCursor(null);
    }

    @Override
    public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
        mAdapter.swapCursor(data);
    }

}
